package protomsg

import (
	"database/sql"
	"encoding/binary"
	math "math"
	"reflect"
)

type IArgs interface {
	// 新的使用字段名就可以更新数据的逻辑
	UpdateField(keyname, field string) error
}

// 单个字段解包数据
func UnPackMsgDataToField(f reflect.Value, msgdata []byte) {
	switch f.Kind() {
	case reflect.Struct:
		if v, ok := f.Addr().Interface().(sql.Scanner); ok {
			v.Scan(msgdata)
		}
	case reflect.Ptr:
		if v, ok := f.Interface().(sql.Scanner); ok {
			v.Scan(msgdata)
		}
	case reflect.Float32:
		v, _ := binary.Uvarint(msgdata)
		f.SetFloat(float64(math.Float32frombits(uint32(v))))
	case reflect.Float64:
		v, _ := binary.Uvarint(msgdata)
		f.SetFloat(float64(math.Float64frombits(uint64(v))))
	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		v, _ := binary.Varint(msgdata)
		f.SetInt(v)
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		v, _ := binary.Uvarint(msgdata)
		f.SetUint(v)
	case reflect.String:
		f.SetString(string(msgdata))
	case reflect.Slice:
		//如果是切片类型，一般都是[]byte
		//如果不是还不知道要怎么处理
		if f.Type().Elem().Kind() == reflect.Uint8 {
			f.SetBytes(msgdata)
		}
	case reflect.Bool:
		f.SetBool(msgdata[0] == 1)

	default:

	}
}

// 设置数据到差量中去
func SetDataModel(md interface{}, msgdata *TableData) {
	vmd := reflect.ValueOf(md).Elem()
	for k, v := range msgdata.Datas {
		f := vmd.FieldByName(k)
		UnPackMsgDataToField(f, v)
	}
}
